/*++

Copyright (c) Microsoft Corporation. 
 
This source code is subject to terms and conditions of the Microsoft
Public License. A copy of the license can be found in the License.txt
file at the root of this distribution. By using this source code in 
any fashion, you are agreeing to be bound by the terms of the Microsoft
Public License.
 
You must not remove this notice, or any other, from this software.

Module Name:

    RS232Target.h

Abstract:

    This module contains the definitions for the code that supports the asynchronous communication
    between the sensor device and the driver.
--*/

#pragma once

// Forward reference
class SensorBaseDriver;

class RS232Target :
    public IRequestCallbackRequestCompletion
{
public:    
    RS232Target();

    ~RS232Target();    

    HRESULT Create(SensorBaseDriver* pBaseDriver,
                   IWDFDevice*    pDevice, 
                   HANDLE         hRS232Port);

    void    Delete();

    HRESULT Start();    

    HRESULT Stop();

    BOOL    IsReady();

    WDF_IO_TARGET_STATE GetState();

    HRESULT SendReadRequest();

    HRESULT SendWriteRequest(BYTE*   pBuffer,
                             size_t  cbBufferSize);

    VOID OnTimerCallback();  
    
    VOID CreatePersistentWorkTimer();

    VOID CleanupPersistentWorkTimer();

    SensorState GetSensorState();

    VOID SetSensorState(SensorState st);

    VOID SetInternalTimer(int iInterval);

public: // IUnknown
    ULONG __stdcall AddRef();
    ULONG __stdcall Release();
    HRESULT __stdcall QueryInterface(REFIID riid, void** ppv);
    bool              m_bDataRcvd; // Set to true each time data is read; false otherwise
    PTP_CLEANUP_GROUP m_cleanupgroup;
    PTP_POOL          m_pool;
    PTP_TIMER         m_timer;
    FILETIME          m_FileDueTime;

    //
    // IRequestCallbackRequestCompletion
    //
    STDMETHOD_ (void, OnCompletion)(IWDFIoRequest*                 pWdfRequest,
                                    IWDFIoTarget*                  pIoTarget,
                                    IWDFRequestCompletionParams*   pParams,
                                    PVOID                          pContext);

private:
    ULONG                          m_cRef;
    SensorBaseDriver*			   m_pBaseDriver;
    BYTE                           m_pReadBuffer[52]; //This buffer size accomodates the sensor packets
    CComPtr<IWDFDevice>            m_pWDFDevice;
    CComPtr<IWDFIoTarget>          m_pFileTarget;
    DWORD						   m_Interval; // Used to detect updated interval
    SensorState					   m_state;

    // This critical section protects the sensor state from concurrent access
    CComAutoCriticalSection  m_SensorStateCriticalSection;
};
